<template>
  <div class="recommendation-carousel">
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="1" animated />
    </div>
    <div v-else-if="!recipes || recipes.length === 0" class="empty-container">
      <el-empty :description="emptyText" />
    </div>
    <el-carousel v-else :interval="5000" type="card" :height="carouselHeight">
      <el-carousel-item
        v-for="recipe in recipes"
        :key="recipe.id"
        class="carousel-item"
      >
        <div class="recipe-card">
          <div class="card-image" @click="handleRecipeClick(recipe)">
            <img
              :src="recipe.imageUrl || defaultImage"
              :alt="recipe.title"
              @error="handleImageError"
            />
            <div class="rating-overlay" v-if="recipe.avgRating">
              <el-rate
                v-model="recipe.avgRating"
                disabled
                text-color="#ff9900"
                :colors="['#ff9900', '#ff9900', '#ff9900']"
                :score-template="recipe.avgRating.toFixed(1)"
              />
            </div>
            <div class="recommendation-overlay" v-if="recipe.recommendationId">
              <el-tag
                size="small"
                effect="dark"
                :type="getRecommendationTypeTag(recipe.recommendationType)"
              >
                {{ getRecommendationTypeText(recipe.recommendationType) }}
              </el-tag>
            </div>
          </div>
          <div class="card-content">
            <h3 class="recipe-title" @click="handleRecipeClick(recipe)">
              {{ recipe.title }}
            </h3>
            <div class="recipe-info">
              <span class="author">{{ recipe.author }}</span>
              <span class="cuisine">{{ recipe.cuisineType }}</span>
            </div>
            <div class="recipe-tags">
              <el-tag v-if="recipe.tasteType" size="small" type="info">{{
                recipe.tasteType
              }}</el-tag>
              <el-tag v-if="recipe.cookingTime" size="small" type="success">{{
                formatTime(recipe.cookingTime)
              }}</el-tag>
              <el-tag v-if="recipe.difficulty" size="small" type="warning">{{
                difficultyText(recipe.difficulty)
              }}</el-tag>
            </div>
            <div
              class="feedback-actions"
              v-if="showFeedback && recipe.recommendationId"
            >
              <el-tooltip content="添加反馈" placement="top">
                <el-button
                  type="primary"
                  size="small"
                  circle
                  icon="ChatDotRound"
                  @click="handleFeedbackClick(recipe)"
                ></el-button>
              </el-tooltip>
            </div>
          </div>
        </div>
      </el-carousel-item>
    </el-carousel>

    <!-- 反馈弹出框 -->
    <el-dialog
      v-model="feedbackDialogVisible"
      title="推荐反馈"
      width="30%"
      :before-close="handleFeedbackDialogClose"
    >
      <p>这个推荐对您有用吗？</p>
      <div class="feedback-options">
        <el-button type="success" @click="submitFeedback('positive')"
          >有用</el-button
        >
        <el-button @click="submitFeedback('neutral')">一般</el-button>
        <el-button type="danger" @click="submitFeedback('negative')"
          >无用</el-button
        >
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleFeedbackDialogClose">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import {
  recordRecommendationClick,
  submitRecommendationFeedback,
} from "@/api/recommendation";

export default {
  name: "RecommendationCarousel",
  props: {
    recipes: {
      type: Array,
      default: () => [],
    },
    loading: {
      type: Boolean,
      default: false,
    },
    emptyText: {
      type: String,
      default: "暂无推荐",
    },
    showFeedback: {
      type: Boolean,
      default: true,
    },
  },
  setup(props, { emit }) {
    const defaultImage =
      "https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png";
    const carouselHeight = "320px";

    // 反馈相关
    const feedbackDialogVisible = ref(false);
    const currentRecommendation = ref(null);

    const handleImageError = (e) => {
      e.target.src = defaultImage;
    };

    const handleRecipeClick = async (recipe) => {
      // 如果有推荐记录ID，调用点击API记录
      if (recipe.recommendationId) {
        try {
          await recordRecommendationClick(recipe.recommendationId);
          console.log("记录推荐点击成功");
        } catch (error) {
          console.error("记录推荐点击失败", error);
        }
      }

      // 触发点击事件
      emit("recipe-click", recipe);
    };

    const handleFeedbackClick = (recipe) => {
      currentRecommendation.value = recipe;
      feedbackDialogVisible.value = true;
    };

    const handleFeedbackDialogClose = () => {
      feedbackDialogVisible.value = false;
      currentRecommendation.value = null;
    };

    const submitFeedback = async (feedback) => {
      if (
        !currentRecommendation.value ||
        !currentRecommendation.value.recommendationId
      ) {
        ElMessage.error("无法提交反馈，推荐ID不存在");
        feedbackDialogVisible.value = false;
        return;
      }

      try {
        await submitRecommendationFeedback(
          currentRecommendation.value.recommendationId,
          feedback
        );
        ElMessage.success("反馈提交成功，谢谢您的参与");
        feedbackDialogVisible.value = false;

        // 触发反馈提交事件
        emit("feedback-submitted", {
          recommendationId: currentRecommendation.value.recommendationId,
          feedback,
        });
      } catch (error) {
        console.error("提交反馈失败", error);
        ElMessage.error("提交反馈失败，请稍后重试");
      }
    };

    const formatTime = (minutes) => {
      if (!minutes) return "未知时间";

      if (minutes < 60) {
        return `${minutes}分钟`;
      } else {
        const hours = Math.floor(minutes / 60);
        const mins = minutes % 60;
        return mins > 0 ? `${hours}小时${mins}分钟` : `${hours}小时`;
      }
    };

    const difficultyText = (level) => {
      const mapping = {
        1: "简单",
        2: "中等",
        3: "困难",
        4: "大师级",
      };
      return mapping[level] || "未知难度";
    };

    const getRecommendationTypeTag = (type) => {
      const typeMap = {
        "health-based": "success",
        "taste-based": "warning",
        "preference-based": "primary",
        "similar-recipe": "info",
        "cuisine-based": "danger",
        random: "",
      };
      return typeMap[type] || "info";
    };

    const getRecommendationTypeText = (type) => {
      const typeMap = {
        "health-based": "健康推荐",
        "taste-based": "口味推荐",
        "preference-based": "偏好推荐",
        "similar-recipe": "相似推荐",
        "cuisine-based": "菜系推荐",
        random: "随机推荐",
      };
      return typeMap[type] || type;
    };

    return {
      defaultImage,
      carouselHeight,
      feedbackDialogVisible,
      currentRecommendation,
      handleImageError,
      handleRecipeClick,
      handleFeedbackClick,
      handleFeedbackDialogClose,
      submitFeedback,
      formatTime,
      difficultyText,
      getRecommendationTypeTag,
      getRecommendationTypeText,
    };
  },
};
</script>

<style scoped>
.recommendation-carousel {
  padding: 10px 0;
}

.loading-container,
.empty-container {
  height: 320px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.carousel-item {
  cursor: pointer;
}

.recipe-card {
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  background-color: #fff;
  transition: transform 0.3s;
}

.recipe-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
}

.card-image {
  height: 60%;
  position: relative;
  overflow: hidden;
  cursor: pointer;
}

.card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.recipe-card:hover .card-image img {
  transform: scale(1.05);
}

.rating-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
  padding: 5px 10px;
  color: white;
}

.recommendation-overlay {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 2;
}

.card-content {
  padding: 12px;
  height: 40%;
  display: flex;
  flex-direction: column;
}

.recipe-title {
  margin: 0 0 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}

.recipe-info {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: #606266;
  margin-bottom: 8px;
}

.author,
.cuisine {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 48%;
}

.recipe-tags {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
  margin-bottom: auto;
}

.feedback-actions {
  margin-top: 8px;
  display: flex;
  justify-content: flex-end;
}

.feedback-options {
  display: flex;
  justify-content: space-around;
  margin: 20px 0;
}

:deep(.el-carousel__item) {
  border-radius: 8px;
}

:deep(.el-carousel__item--card.is-active) {
  transform: scale(1.05);
  z-index: 2;
}
</style>
